import com.sun.xml.internal.fastinfoset.tools.StAX2SAXReader;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import sun.nio.ch.IOUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class Tool {
    private static String workFolder;
    private static SAXReader reader = new SAXReader();

    public static void main(String[] args) {
        System.out.println("Hello POB2CN!");
        workFolder = System.getProperty("user.dir");
        System.out.println("workFolder: " + workFolder);
        updateManifest();
    }

    public static void updateManifest() {
        try {
            File[] files = new File(workFolder + "/ZdDroid").listFiles();
            if (files == null) return;
            //files = insertElementF(files,new File(workFolder+"/SimpleGraphic.dll"));
            Document document = reader.read(new File(workFolder + "/ZdDroid/manifest_cn.xml"));

            for (File f : files) {
                File[] filesn;
                if (f.isDirectory()) {
                    filesn = f.listFiles();
                    if (filesn == null) continue;
                } else {
                    filesn = new File[]{f};
                }
                for (File f2 : filesn) {

                    if (!f2.isDirectory() && f2.exists()) {
                        String filePath = f2.getAbsolutePath().replace("\\", "/");
                        if (filePath.contains(".xml") || filePath.contains(".ttf")) continue;
                        //String checksum = getFileSha1(f);
                        String checksum = DigestUtils.sha1Hex(new FileInputStream(f2));

                        boolean isNewFile = true;
                        Iterator it = document.getRootElement().elementIterator();
                        while (it.hasNext()) {
                            Element el = (Element) it.next();
                            if (!el.getName().equals("File")) continue;
                            String value = el.attributeValue("name");
                            if (filePath.contains(value)) {
                                String orig_cheksum = el.attributeValue("sha1");
                                if (!checksum.equals(orig_cheksum)) {
                                    System.out.println("Update : " + filePath + " CheckSum:" + checksum);
                                    el.attribute("sha1").setValue(checksum);
                                }
                                isNewFile = false;
                                break;
                            }
                        }
                        if (!isNewFile) continue;

                        System.out.println("ADD : " + filePath + " CheckSum:" + checksum);

                        String field;
                        Element addElement = document.getRootElement().addElement("File");
                        addElement.addAttribute("sha1", checksum);
                        field = filePath.replace((workFolder + "\\").replace("\\", "/"), "");//filePath.substring(filePath.lastIndexOf("/"),filePath.length());
                        addElement.addAttribute("name", field);
                        field = filePath.contains(".dll") ? "runtime" : "program";
                        addElement.addAttribute("part", field);
                    }
                }
            }
            File outFile = new File(workFolder + "/ZdDroid/manifest_cn.xml");
            if (outFile.exists()) outFile.delete();
            FileOutputStream out = new FileOutputStream(outFile);
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("utf-8");
            XMLWriter writer = new XMLWriter(out, format);
            writer.write(document);
            writer.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static File[] insertElementF(File orig[], File element) {

        int length = orig.length;

        File destination[] = new File[length + 1];

        System.arraycopy(orig, 0, destination, 0, length);

        destination[length] = element;
        return destination;
    }

    public static String getFileSha1(File file) throws Exception {
        byte[] bytes = new byte[(int) file.length()];
        IOUtils.readFully(new FileInputStream(file), bytes);
        MessageDigest digest = MessageDigest.getInstance("SHA1");
        digest.update(bytes);
        BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(16);
    }

}
